import { Body, ResponseType, fetch } from '@tauri-apps/api/http'
import { date_with_timestamp } from './utils';

const baseURL = 'http://local.hontech-rdcenter.com:23331';

const ACCOUNT = "root";
const PWD = "root1234";

const ID_MAIN = 6;
const ID_HEAT = 5;
const ID_WEIGHT = 7;

let MY_TOKEN = '';

interface User {
    id: number,
    name: string,
    account: string,
    pwd_enc: string,
}

interface LoginRes {
    user: User,
    token: string,
}

export interface DevFile {
    id: number,
    name: string,
    create_timestamp: number,
    size: number,
    version: string,
    description: string,
}

export interface DevFileInfo {
    id: number,
    name: string,
    date: string,
    size: number,
    version: string,
    description: string,
}

async function login() {
    const res = await fetch<LoginRes>(`${baseURL}/api/user/login`, {
        method: 'POST',
        body: Body.json({
            account: ACCOUNT,
            pwd: PWD
        }),
        timeout: 2000,
        responseType: ResponseType.JSON
    });
    const user_res = res.data;
    MY_TOKEN = user_res.token;
}

async function get<T>(url: string) {
    const ret = await fetch<T>(url, {
        method: 'GET',
        timeout: 10000,
        headers: {
            "token": MY_TOKEN
        },
        responseType: ResponseType.JSON
    });
    const resp = ret.headers['resp'];
    if (resp != 'ok') {
        throw `执行失败:${resp}`
    }
    return ret.data;
}

export async function query_raw(type_id: number) {
    
    try {
        return await get<DevFile[]>(`${baseURL}/api/dev_file/query?type_id=${type_id}`);
    } catch (msg) {
        await login();
        return await get<DevFile[]>(`${baseURL}/api/dev_file/query?type_id=${type_id}`);
    }
}

export async function query(type_id: number) {
    const result = await query_raw(type_id);
    return result.map<DevFileInfo>((df) => { 
        return {
            id: df.id,
            name: df.name,
            date: date_with_timestamp(df.create_timestamp),
            size: df.size,
            version: df.version,
            description: df.description
        }
    });



}

export async function download(id: number) {
    const ret = await fetch<number[]>(`${baseURL}/api/dev_file/get?id=${id}`, {
        method: 'GET',
        responseType: ResponseType.Binary,
        headers: {
            'token': MY_TOKEN
        },
    });
    return ret.data;
}

export async function query_main() {
    return await query(ID_MAIN);
}

export async function query_heat() {
    return await query(ID_HEAT);
}

export async function query_weight() {
    return await query(ID_WEIGHT);
}